Ext.namespace('SpeciesObservation');

SpeciesObservation.speciesForm = function(config){
	var speciesTpl = new Ext.XTemplate(
			'<tpl for="."><div class="search-item">'
		,	'<div class="vernacular">{name}'
		,	'</div>'
		,	'<div class="scintificName">{genus} {species}</div>'
		,	'</div></tpl>'
	);

	var localityTpl = new Ext.XTemplate(
			'<tpl for="."><div class="search-item">'
		,	'<div class="vernacular">{name}</div><div class="scintificName">{county}</div>'
		,	'</div></tpl>'
	);

	var genderStore = new Ext.data.ArrayStore({
			fields: ['gender']
		,	data: [['Male'], ['Female'], ['Mixed'], ['Unknown']]
	});

	var ageStore = new Ext.data.ArrayStore({
			fields: ['age']
		,	data: [['Juvenile'], ['Adult'], ['Mixed'], ['1st Year'], ['2nd Year'], ['3rd Year'], ['Unknown']]
	});

	var stateStore = new Ext.data.ArrayStore({
			fields: ['abbr', 'state',]
		,	data: Ext.exampledata.states
	});

	var speciesStore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: Config.baseUrl + 'resources/api/api.php'
			})
		,	baseParams: {
					cmd: "list"
				,	type: "vernacular" 
			}	
		,	reader: new Ext.data.JsonReader({
					root: 'data'
				,	totalProperty: 'totalCount'
			}, [
					{name: 'name', mapping: 'name'}
				,	{name: 'genus', mapping: 'genus'}
				,	{name: 'species', mapping: 'species'}
				,	'match'
			])
	});

	this.parishStore = new Ext.data.JsonStore({
			proxy: new Ext.data.HttpProxy({
				url: Config.baseUrl + 'resources/api/api.php'
			})
		,	baseParams: {
					cmd: "list"
				,	type: "parish"
			}
		,	root: 'data'	
		,	autoLoad: true
		,	fields: ['name']
	});

	this.localityStore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
					url: Config.baseUrl + 'resources/api/api.php'
			})
		,	baseParams: {
					cmd: "list"
				,	type: "locality"
			}	
		,	reader: new Ext.data.JsonReader({
					root: 'data'
				,	totalProperty: 'totalCount'
			}, [
					{name: 'name', mapping: 'name'}
				,	{name: 'county', mapping: 'county'}
			])
	});
	
	Ext.apply(this, config, {
			labelWidth: 160
		,	defaultType: 'textfield'
		,	padding: '10px'
		,	autoScroll: true
		,	defaults:{
					anchor: '-18px'
				,	scope: this
			}
		,	getOccurClicked: false	
		,	items: [{	
				fieldLabel: '*Species (English Name)'
			,	name: 'vernacularName'
			,	xtype: 'combo'
			,	typeAhead: false
			,	loadingText: 'Searching...'
		//	,	pageSize: 10
			,	hideTrigger: true
			,	tpl: speciesTpl
			,	store: speciesStore
			,	allowBlank: false
			,	minChars: 2
			,	itemSelector: 'div.search-item'
			,	dataEntry: false
			,	listeners: {
					select: function(index, data){
						this.getForm().setValues({vernacularName: data.data.name});
						this.getForm().setValues({species: data.data.species});
					} 
				,	scope: this	
				}
			}, {
					xtype: 'label'
				,	html: 'Only select values from the drop down list.'
				,	fieldLabel: '&nbsp;'
				,	labelSeparator: ''
			}, {	
					xtype: 'combo'
				,	fieldLabel: 'State'
				,	name: 'state'
				,	store: stateStore
				,	displayField:'state'
				,	valueField: 'abbr'
				,	typeAhead: true
				,	mode: 'local'
				,	forceSelection: true
				,	triggerAction: 'all'
				,	selectOnFocus:true
				,	hiddenName: 'state'
				,	hiddenValue: 'LA'
				,	value : 'LA'
			}, {
					xtype: 'hidden'
				,	name: 'species'
			}, {
					fieldLabel: '*Locality'
				, name: 'locality'
				,	allowBlank: false				
			}, {
					xtype: 'xtwincombo'
				,	fieldLabel: 'Parish'
				,	name: 'county'
				,	forceSelection: true
				,	store: this.parishStore
				,	displayField: 'name'
				,	typeAhead: false
				,	mode: 'local'
				,	hideTrigger2: false
				,	triggerAction: 'all'				
			}, {
					xtype: 'datefield'
				,	fieldLabel: '*First Date'
				,	name: 'dateObserved'
//				,	value: new Date()
				,	allowBlank: false
			}, {
					fieldLabel: 'All Dates Observed'
				,	name: 'verbatimDate'	
			}, {
					fieldLabel: 'Number seen'
				,	name: 'numberSeen'
			}, {
					fieldLabel: 'Observer(s)'
				,	name: 'observers'					
			}, {
					xtype: 'combo'
				,	fieldLabel: 'Sex'
				,	name: 'sex'
				,	displayField:'gender'
				,	valueField: 'gender'
				,	typeAhead: true
				,	mode: 'local'
				,	store: genderStore
				,	forceSelection: true
				,	triggerAction: 'all'
				,	selectOnFocus:true
				,	value : ''
			}, {
					xtype: 'combo'
				,	fieldLabel: 'Age'
				,	name: 'age'
				,	displayField:'age'
				,	valueField: 'age'
				,	typeAhead: true
				,	mode: 'local'
				,	store: ageStore
				,	forceSelection: true
				,	triggerAction: 'all'
				,	selectOnFocus:true
				,	value : ''
			}, {	
					xtype: 'checkboxgroup'
				,	fieldLabel: 'Detection Type'
				,	itemCls: 'x-check-group-alt'
				,	columns: 3
				,	items: [
							{boxLabel: 'Sight Rec.', name: 'sightRec',	inputValue: 1}
						,	{boxLabel: 'Heard', name: 'heardOnly',	inputValue: 1}
						,	{boxLabel: 'Specimen', name: 'specimen', inputValue: 1}
					]
			}, {	
					xtype: 'compositefield'
				,	anchor: '-18px'
//				,	anchor: '100%'
				,	items: [{
						xtype: 'checkbox'
					,	boxLabel: 'Photo'
					,	name: 'photo'
					,	inputValue: 1
					,	flex: 1 
					},{
						xtype: 'displayfield'
					,	value: 'URL: '
					,	flex: 1
					,	width: 30
					},{
						xtype: 'textfield'
					,	name: 'photoUri'
					,	width: 200
					}]
			},{	
					xtype: 'compositefield'
				,	anchor: '-18px'
//				,	anchor: '100%'	
				,	items: [{
						xtype: 'checkbox'
					,	boxLabel: 'Video'
					,	name: 'video'
					,	inputValue: 1
					,	flex: 1
					},{
						xtype: 'displayfield'
					,	value: 'URL: '
					,	flex: 1
					,	width: 30
					},{
						xtype: 'textfield'
					,	name: 'videoUri'
					,	width: 200
					}]
			},{	
					xtype: 'compositefield'
				,	anchor: '-18px'
//				,	anchor: '100%'	
				,	items: [{
						xtype: 'checkbox'
					,	boxLabel: 'Audio Recording'
					,	inputValue: 1
					,	name: 'audioRec'
					,	flex: 1
					},{
						xtype: 'displayfield'
					,	flex: 1	
					,	value: 'URL: '
					,	width: 30
					},{
						xtype: 'textfield'
					,	name: 'audioRecUri'
					,	width: 200
					}]
			}, {	
					fieldLabel: 'Plumage Characteristics' 
				,	name: 'characteristics'
				,	xtype: 'textarea'
				,	width: 100				
			},/*{
				fieldLabel: 'Songs'
			,	xtype: 'panel'
			,	ref: 'refsongpanel'
			}, */{	
					xtype: 'textarea'
				,	fieldLabel: 'Description/Details' 
				,	name: 'description'
				,	height: 100
			}, {
					fieldLabel: 'Significance' 
				,	name: 'significance'
			}, {
					xtype: 'textarea'
				,	fieldLabel: 'Contact Information (E-mail, Phone, and/or Address)'
				,	width: 100
				,	name: 'contactInfo'
			}, {
					xtype: 'label'
				,	html: 'If you have trouble reading the two words below you may select the () button and get two new words.'
				,	fieldLabel: '&nbsp;'
				,	labelSeparator: ''
			}, {
					xtype: 'hidden'
				,	name: 'auth'
			}]
		,	fbar: {
				xtype: 'toolbar'
			,	items: [{	
						xtype: 'button'
					,	iconCls: 'historicalCard'
					,	text: 'Flag as Backside of Card'	
					,	ref: '../refFlagCard'
					,	hidden: true	
					,	scope: this
					,	handler: this.linkImage
/*					
				}, {
					xtype: 'button'
				,	text: 'Clear'
				,	scope: this
				,	handler: function(){
						this.getForm().reset();
					//	this.refsongpanel.body.update('');
					}		
*/					
				}, {	
						xtype: 'button'
					,	ref: '../refSave'
					,	iconCls: 'icon_save'	
					,	scope: this	
				}, {	
						xtype: 'button'
					,	text: 'Cancel'
					,	ref: '../refCancel'
					,	hidden: true
					,	scope: this	
				}]	
			
		}
	});
	
	SpeciesObservation.speciesForm.superclass.constructor.call(this, config);

}

Ext.extend(SpeciesObservation.speciesForm, Ext.form.FormPanel, {

	sendData: function(){
		var val = this.getForm().getValues();
		var params = {};
		Ext.apply(params, {
			cmd: 'newOccurrence'
		}, val);

		if(this.getForm().isValid()){
			var myMask = new Ext.LoadMask(this.body, {msg: 'Saving observation...'});
			myMask.show();
			Ext.Ajax.request({
					url: Config.baseUrl + 'resources/api/api.php'
				,	method: 'POST'
				,	scope: this
				,	params: params
				,	success: function(responseObject){
						var o = Ext.decode(responseObject.responseText);
						if(o.success){
							Ext.Msg.alert('Status', 'Observation Received<br>Ref #: ' + o.id + '<br>You may now enter a new observation.');
							Recaptcha.reload();
							Recaptcha.focus_response_field();
							this.getForm().reset();
						} else{
							Recaptcha.reload();
							Recaptcha.focus_response_field();
							Ext.Msg.alert("Notice", o.error);
						}
						myMask.hide();	
					}
				,	failure: function(res){
						myMask.hide();
						Ext.Msg.alert("Error", "Fatal Error.");
					}
			}, this);
		} else {
			Ext.Msg.alert('Notice', 'Please enter required values.');
		}
	}

	,	updateData: function(id, cmd, msg, notice, auth){
			var val = this.getForm().getValues();
			var params = {};
			Ext.apply(params, {
					cmd: cmd
				,	id: id
				,	auth: auth
			},val);

			if(this.getForm().isValid()){
				var myMask = new Ext.LoadMask(this.body,{msg: msg});
				myMask.show();
				Ext.Ajax.request({
						url: Config.baseUrl + 'resources/api/api.php'
					,	method: 'POST'
					,	scope: this
					,	params: params
					,	success: function(responseObject){
							var o = Ext.decode(responseObject.responseText);
							if(o.success){
								SpeciesObservation.Notice.msg("Success", notice);
								this.getForm().reset();
							}	
							myMask.hide();
						}
					,	failure: function(res){
							SpeciesObservation.Notice.msg("Error", "Fatal Error.");
							myMask.hide();
						}
				}, this);
			} else {
				SpeciesObservation.Notice.msg('Notice','Please Enter Valid Values');
			}
		}
	
	,	setImageToQueue: function(id){
			Ext.Ajax.request({
					url: Config.baseUrl + 'resources/api/api.php'
				,	method: 'POST'
				,	scope: this
				,	params: {
						cmd: 'queue_set_image'
					,	occurrenceId: id
					}
				,	success: function(responseObject){}
				,	failure: function(res){
						SpeciesObservation.Notice.msg("Error", "Fatal Error.");
					}
			}, this);
		}
	,	addRecaptcha: function(){
			var recaptchaItem = {
					xtype: 'recaptcha'
				,	fieldLabel: 'Recaptcha'
				,	ref: 'refRecaptcha'
				,	name: 'recaptcha'
				,	id: 'recaptcha'
				,	publickey: Config.Recaptcha.publicKey || ""
				,	theme: 'white'
				,	lang: 'en'
			}
			this.add(recaptchaItem);
		}
	,	getOccuranceImage: function(){
			Ext.Ajax.request({
					url: Config.baseUrl + 'resources/api/api.php'
				,	method: 'POST'
				,	scope: this
				,	params: {
						cmd: 'queue_get_image'
					}
				,	success: function(responseObject){
						var o = Ext.decode(responseObject.responseText);
						if(o.success){
							this.setTitle('Species Entry: ID #' + o.data.occurrenceId);
							this.refSave.enable();
							this.refFlagCard.enable();
							this.getForm().reset();
							var img = o.data.path + o.data.filename;
							this.occurrenceId = o.data.occurrenceId;
							this.auth = o.data.auth;
							this.loadImage(o.data);
							this.getOccurClicked = true;
						}else{
							this.setTitle('Species Entry');
							SpeciesObservation.Notice.msg('Notice', o.error.msg);
							this.refSave.disable();
							this.refFlagCard.disable();
							this.resetImage();
						}
					}
				,	failure: function(res){	
						this.setTitle('Species Entry');
						SpeciesObservation.Notice.msg('Error', 'Error in connection.');
					}
			}, this);
		}
		
	,	loadImage: function(rec){
			var arr = [];
			this.ownerCt.panel.refresh();
			if(!Ext.isEmpty(rec.filename)) arr.push([Config.s3BaseUrl + rec.path + rec.filename]);
			if(!Ext.isEmpty(rec.filename2)) arr.push([Config.s3BaseUrl + rec.path2 + rec.filename2]);
			if(!Ext.isEmpty(rec.filename3)) arr.push([Config.s3BaseUrl + rec.path3 + rec.filename3]);
			if(!Ext.isEmpty(rec.filename4)) arr.push([Config.s3BaseUrl + rec.path4 + rec.filename4]);
			if(!Ext.isEmpty(rec.filename5)) arr.push([Config.s3BaseUrl + rec.path5 + rec.filename5]);		
			this.ownerCt.panel.store.loadData(arr);
		}

		,	resetImage: function(){
				var arr = [];
				this.ownerCt.panel.refresh();
				this.ownerCt.panel.store.loadData(arr);
			}

		,	linkImage: function(){
				if(this.getOccurClicked){
					Ext.Ajax.request({
							url: Config.baseUrl + 'resources/api/api.php'
						,	method: 'POST'
						,	scope: this
						,	params: {
									cmd: 'linkImage'
								,	occurrenceId: this.occurrenceId
								,	auth: this.auth
							}
						,	success: function(responseObject){
								var o = Ext.decode(responseObject.responseText);
								if(o.success){
//									var img = o.data.path;
//									this.loadImage(img);
									this.getOccurClicked = false;
									this.getOccuranceImage();
								} else {
									this.resetImage();
									SpeciesObservation.Notice.msg('Notice', 'Image Not Available.');
								}
							}
						,	failure: function(res){	
								SpeciesObservation.Notice.msg('Error', 'Error in connection.');
							}
					}, this);
				}else {
					SpeciesObservation.Notice.msg('Notice', 'Get Ouccurance image first.');
				}
			}

});